// 临时人员建档 API
const API_BASE_URL = "http://192.168.0.119:86";
const AUTH_TOKEN =
  "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyOCIsImxvZ2luX3VzZXJfa2V5IjoiZWU3MmJmYjMtYWI5OC00MGYzLTkwYzQtZjlkMGY5ZjdmOWJjIn0.xg3iR-GWuFMD2ZNYiBu7lREO-cWGYHvSdDCTVO6k7Rjwm3RLQ0qrTKe5W49T_w3kHxV1v-wQLs6ELmiwOkXjrg";

export const addTemporaryUser = async (userData) => {
  try {
    const response = await fetch(`${API_BASE_URL}/terminal/add/temporary`, {
      method: "POST",
      headers: {
        Authorization: AUTH_TOKEN,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(userData),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error("添加临时用户失败:", error);
    throw error;
  }
};

// 获取排除学院的部门列表信息
export const getDepartmentWaitCount = async () => {
  try {
    const response = await fetch(
      `${API_BASE_URL}/api/user/listExcludeColleges`,
      {
        method: "POST",
        headers: {
          Authorization: AUTH_TOKEN,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          deptName: "科",
          orderNum: 1
        }),
      }
    );

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error("获取部门等候人数失败:", error);
    throw error;
  }
};

// 提交预约信息
export const submitBooking = async (userId, deptName, departmentId, token) => {
  try {
    // 获取当前日期，格式为 YYYY-MM-DD
    const currentDate = new Date().toISOString().split('T')[0]
    
    const response = await fetch(
      `${API_BASE_URL}/api/booking/submit`,
      {
        method: "POST",
        headers: {
          Authorization: token ? `Bearer ${token}` : AUTH_TOKEN,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          id: userId,
          deptName: deptName,
          departmentId: departmentId,
          bookingDate: currentDate,
          businessflag: "normal",
          description: deptName,
          timeSlotId: 2
        }),
      }
    );

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error("提交预约信息失败:", error);
    throw error;
  }
};

// 获取部门的业务类型列表
export const getDepartmentBizCategory = async (deptId) => {
  try {
    const response = await fetch(
      `${API_BASE_URL}/api/user/type/biz_category/dept/${deptId}`,
      {
        method: "GET",
        headers: {
          Authorization: AUTH_TOKEN,
        },
      }
    );

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error("获取部门业务类型失败:", error);
    throw error;
  }
};

// 获取选中部门的叫号信息（传入terminalId和departmentId）
export const getDepartmentCallInfo = async (terminalId, departmentId) => {
  try {
    const url = new URL(`${API_BASE_URL}/terminal/department/call`);
    if (terminalId) {
      url.searchParams.append("terminalId", terminalId);
    }
    if (departmentId) {
      url.searchParams.append("departmentId", departmentId);
    }

    const response = await fetch(url.toString(), {
      method: "GET",
      headers: {
        Authorization: AUTH_TOKEN,
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error("获取部门叫号信息失败:", error);
    throw error;
  }
};

// 终端取号（支持userId和terminalId）
export const takeNumber = async (userId, terminalId, idNumber, departmentId) => {
  try {
    const url = new URL(`${API_BASE_URL}/terminal/take/number`);
    
    // 根据用户类型传递不同参数
    if (userId) {
      url.searchParams.append("userId", userId);
    }
    if (terminalId) {
      url.searchParams.append("terminalId", terminalId);
    }
    if (idNumber) {
      url.searchParams.append("idNumber", idNumber);
    }
    if (departmentId) {
      url.searchParams.append("departmentId", departmentId);
    }

    const response = await fetch(url.toString(), {
      method: "GET",
      headers: {
        Authorization: AUTH_TOKEN,
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error("终端取号失败:", error);
    throw error;
  }
};

// 打印小票【模拟】
export const printTicket = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/terminal/print`, {
      method: "GET",
      headers: {
        Authorization: AUTH_TOKEN,
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error("打印小票失败:", error);
    throw error;
  }
};

// 用户登录（支持多种认证方式）
export const userLogin = async (username, password, authMethod, idNumber, cardNumber) => {
  try {
    const requestBody = {
      authMethod: authMethod
    }
    
    // 根据认证方式添加不同参数
    if (authMethod === 'unified') {
      requestBody.xh = username
      requestBody.password = password
    } else if (authMethod === 'id') {
      requestBody.idNumber = idNumber
    } else if (authMethod === 'card') {
      requestBody.cardNumber = cardNumber
    }
    
    const response = await fetch(`${API_BASE_URL}/api/auth/login`, {
      method: "POST",
      headers: {
        Authorization: AUTH_TOKEN,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(requestBody),
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    return await response.json()
  } catch (error) {
    console.error("用户登录失败:", error)
    throw error
  }
}

// 人脸识别登录
export const faceLogin = async (faceData) => {
  try {
    const response = await fetch(`${API_BASE_URL}/api/auth/face-login`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: AUTH_TOKEN,
      },
      body: JSON.stringify({
        key: faceData || {}
      })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error("人脸识别登录失败:", error);
    throw error;
  }
};
